// packageA/pages/enroll/enroll.js
const db = wx.cloud.database()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    from: {
      username: '',
      password: '',
      name: '',
      loginDate: '',
      type: '',
      workList: [],
      avater: 'cloud://xiaotu-1gkf9sf353dac-2bf89bf5839.7869-xiaotu-1gkf9sf353dac-2bf89bf5839-1307545812/头像 男孩.png',
      workLableList: []
    },
    loading: false,
    selectList: [],
    ispassword: true
  },
  changeIspassword(){
    this.setData({ispassword: !this.data.ispassword})
  },
  usernameChange(e){
    this.setData({['from.username']: e.detail})
  },
  passwordChange(e){
    this.setData({['from.password']: e.detail})
  },
  nameChange(e){
    this.setData({['from.name']: e.detail})
  },
  changeAva(e){
    this.setData({
      ['from.avater']: e.currentTarget.dataset.avater
    })
  },
  onChange(e){
    this.setData({
      ['from.type']: e.detail
    })
  },
  sumbit(){
    if(!this.data.from.username){
      wx.showToast({ title: '请输入账号', icon: 'none' });
      return
    }
    if(!this.data.from.password){
      wx.showToast({ title: '请输入密码', icon: 'none' });
      return
    }
    if(!this.data.from.name){
      wx.showToast({ title: '请输入昵称', icon: 'none' });
      return
    }
    if(this.data.from.workList.length == 0){
      wx.showToast({ title: '请选择工地', icon: 'none' });
      return
    }
    if(!this.data.from.type){
      wx.showToast({ title: '请选择类型', icon: 'none' });
      return
    }
    console.log(this.data.from);
    this.setData({
      loading: true
    })
    this.uploadToCloud()
  },
  getSelectList(e){
    this.setData({
      ['from.workList']: e.detail.map(i=>{return i.id}),
      ['from.workLableList']: e.detail.map(i=>{return i.name})
    })
  },
   // 上传图片
   uploadToCloud() {
    let that = this
    wx.cloud.callFunction({
      name: 'getOpenid',
      success(res){
        let openid = res.result.openid
        let date = Date.now()
        that.setData({['from.loginDate']: openid + date})
        let data = {
          username: that.data.from.username,
          password: that.data.from.password,
          name: that.data.from.name,
          loginDate: that.timestampToTime(date),
          type: that.data.from.type,
          avater: that.data.from.avater,
          workList: that.data.from.workList,
          workLableList: that.data.from.workLableList
        }
        db.collection('user').add({data: data}).then(d=>{
          wx.showToast({ title: '添加成功', icon: 'none' });
          that.setData({
            loading: false
          })
        }).catch(err=>{
          console.log(err);
          wx.showToast({ title: '资源不足', icon: 'none' });
          that.setData({
            loading: false
          })
        })
        
      }
    })
  },
  timestampToTime(timestamp) {
    timestamp = timestamp ? timestamp : null;
    let date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
    let Y = date.getFullYear() + '-';
    let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
    let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
    let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
    let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
    return Y + M + D + h + m + s;
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getworkList()
  },
  close(){
    this.selectComponent('#mySelect').close()
  },
  getworkList(){
    let count = 0
    db.collection('siteInfo').count().then(res=>{
      count = res.total
      if(count > 0){
        let asycList = []
        for(let i = 0; i < count; i += 20){
          asycList.push(new Promise((resolve, reject) => {
            db.collection('siteInfo').orderBy('date', 'desc').skip(i).get({
              success:function(res) {
                resolve(res.data)
              }
            })
          }))
        }
        Promise.all(asycList).then(res=>{
          console.log(res[0]);
          this.setData({selectList: res[0]})
        })
      }
    })

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})